package com.ruoyi.biz.service;

import com.ruoyi.biz.domain.BizProject;
import com.ruoyi.biz.mapper.BizTopicMapper;
import com.ruoyi.biz.model.req.StatReq;
import com.ruoyi.biz.model.resp.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

import static com.ruoyi.common.utils.SecurityUtils.getUserId;
import static com.ruoyi.common.utils.SecurityUtils.isAll;

/**
 * @author tianl
 * @date 2025/1/3
 * @description:
 */
@Service
public class CalendarService {
    @Autowired
    private BizProjectService bizProjectService;
    @Autowired
    private BizTopicMapper bizTopicMapper;

    public List<CalenderResp> getTopicList(Integer year, Integer month, String type) {
        List<BizProject> projectList = bizProjectService.listStat(new StatReq());
        if (CollectionUtils.isEmpty(projectList)) {
            return new ArrayList<>();
        }
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month - 1, 1); // 设置为该月的第一天

        Date firstDay = calendar.getTime(); // 获取该月第一天的 Date 对象

        calendar.add(Calendar.MONTH, 1);
        calendar.set(Calendar.DAY_OF_MONTH, 0);

        Date lastDay = calendar.getTime(); // 获取该月最后一天的 Date 对象

        List<Long> projectIds = projectList.stream().map(BizProject::getId).collect(Collectors.toList());
        List<CalenderResp> calenders = bizTopicMapper.listTime(projectIds, firstDay, lastDay, isAll() ? "1" : getUserId() + "");
        calenders.forEach(c -> {
            c.setTitle(c.getTitleReal());
            if (c.getStatus() != 2 && c.getDue()) {
                c.setBackgroundColor("#fb4545");
                c.setBorderColor("#fb4545");
            } else if (c.getStatus() != 2 && c.getWarn()) {
                c.setBackgroundColor("#ffb91a");
                c.setBorderColor("#ffb91a");
            }
        });
        if (type.equals("1")) {
            calenders = calenders.stream().filter(r -> !r.getStatus().equals(2))
                    .filter(CalenderResp::getDue).collect(Collectors.toList());
            return calenders;
        } else if (type.equals("2")) {
            calenders = calenders.stream().filter(r -> !r.getStatus().equals(2))
                    .filter(r -> !r.getDue())
                    .filter(CalenderResp::getWarn).collect(Collectors.toList());
            return calenders;
        } else if (type.equals("3")) {
            calenders = calenders.stream().filter(r -> r.getStatus().equals(2))
                    .collect(Collectors.toList());
            return calenders;
        }
        return calenders;
    }

}
